import { useState } from "react";
import { View } from "@tarojs/components";
import { useLoad } from "@tarojs/taro";
import AtTabs from "taro-ui/lib/components/tabs";
import AtTabsPane from "taro-ui/lib/components/tabs-pane";
import AtSearchBar from "taro-ui/lib/components/search-bar";
import CustomTabBar from "@/components/CustomTabBar";
import GoodsItem from "@/components/GoodsItem";
import { getGoodsTabListApi, getGoodsListApi } from "@/apis/goods";
import "./index.scss";

export default function Index() {
  const [searchText, setSearchText] = useState("");
  const [currentTab, setCurrentTab] = useState(0);
  const [tabList, setTabList] = useState([]);
  const [goodsList, setGoodsList] = useState([]);

  const getTabList = async () => {
    const res = await getGoodsTabListApi();
    setTabList(res.data);
  };

  const getGoodsList = async (id, keyword) => {
    const res = await getGoodsListApi(id, keyword);
    setGoodsList(res.data);
  };

  useLoad(() => {
    getTabList();
    getGoodsList(1);
    console.log("Page loaded.");
  });

  const handleClick = (index) => {
    setCurrentTab(index);
    getGoodsList(tabList[index].id);
  };

  const handleSearch = () => {
    console.log("Searching for:", searchText);
    getGoodsList(1, searchText);
    // Implement search functionality here if needed
  };



  console.log("Tab List:", tabList);
  console.log("Goods List:", goodsList);

  return (
    <View>
      <CustomTabBar contentClassName='index' currentPage={0}>
        <View className='index-search'>
          <AtSearchBar
            placeholder='输入商品编码搜索...'
            value={searchText}
            onChange={(value) => setSearchText(value)}
            onActionClick={handleSearch}
          />
        </View>
        <AtTabs
          current={currentTab}
          tabList={tabList}
          height='500px'
          onClick={handleClick}
          tabDirection='vertical'
          scroll
        >
          {tabList.map((tab, index) => (
            <AtTabsPane tabDirection='vertical' current={currentTab} index={index} key={`${index}`}>
              {goodsList?.map((item) =>{
                return (
                  <GoodsItem key={item.id} imageUrl={item.imageUrl} code={item.code} />
                );
              })}
            </AtTabsPane>
          ))}
        </AtTabs>
      </CustomTabBar>
    </View>
  );
}
